const ajax = function(options={}){
    let {url,type='get',params,headers,data} = options;
    if(params){
        url+="?"+Object.keys(params).map(key=>key+"="+params[key]).join("&")
    }
    return new Promise(resolve=>{
        const xhr = new XMLHttpRequest();
        xhr.responseType = "json";
        xhr.open(type,url);
        if(headers){
            for(let key in headers){
                xhr.setRequestHeader(key,headers[key])
            }
        }
        if(type === "post"){
            xhr.setRequestHeader("Content-Type","application/json");
            xhr.send(JSON.stringify(data));
        }else{
            xhr.send();
        }

        xhr.onload = function(){
            resolve(xhr.response);
        }
    })
}
ajax.get = function(url,config){
    return ajax({
        url,
        ...config
    });
}
ajax.post = function(url,data,config){
    return ajax({
        url,
        data,
        type:"post",
        ...config,
    })
}
export default ajax;